/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package web;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kyakya.Post;
import kyakya.User;
import kyakya.manager.DBManager;

/**
 *
 * @author Winzelric
 */
@WebServlet(name = "GetContent", urlPatterns = {"/GetContent"})
public class GetContent extends HttpServlet {

  public static String getExtension(String file) {
    int dotIndex = file.lastIndexOf(".");
    String extension = file.substring(dotIndex + 1, file.length());
    return extension;
  }

  public static String getFileName(String file) {

    int dotIndex = file.lastIndexOf(".");
    int fileSeparatorIndex = file.lastIndexOf(File.separator);
    String fileName = file.substring(fileSeparatorIndex + 1,
            dotIndex);
    return fileName;

  }

  public static String getContent(int userID, int postID) {
    StringBuilder sb = new StringBuilder();
    try {
      User user = DBManager.getUserByID(userID);
      Post post = DBManager.getPost(postID);

      String content = vungsi.ambilKonten(post.getContent());
      User author = DBManager.getUserByID(post.getAuthorID());

      content.replace("/watch?v=", "/v/");
      sb.append("<h2><a class='content_title' href='content.jsp?pid=" + postID + "' >" + post.getTitle() + "</a></h2><br/>");
      sb.append("<div class='content_tag'>" + post.getTags() + "</div>");
      sb.append("<div class='content_author'><a href='profile.jsp?id=" + author.getId() + "'> by " + author.getUsername() + "</a></div>");
      sb.append("<div class='content_date'> created in " + post.getCreateTime() + "</div>");
      sb.append("<div class='content_number'>Like " + post.getLikeCount() + "</div>");
      sb.append("<div class='content_number'>Disike " + post.getDislikeCount() + " </div>");
      sb.append("<div class='content_number'>Commented by " + post.getCommentCount() + " people </div>");
      sb.append(content + "<br/>");
      if (userID != 0) {
        sb.append("<input type='button' value='Like' OnClick='gaEngga(" + postID
                + ", " + userID + ")' />"
                + "<input type='button' value='Dislike' OnClick='Engga(" + postID + ", " + userID + ")' />");
      }


      // nampilin title, date, author
      // jumlah komentar, jumlah lik dislike, button
      // kontent, 


    } catch (Exception e) {
      e.printStackTrace();
    }


    return sb.toString();
  }

  public int[] computePrefix(char[] w) {
    int[] t = new int[w.length];
    int i = 2, j = 0;
    t[0] = -1;
    if (t.length > 1) {
      t[1] = 0;
    }
    
    while (i < w.length) {
      if (w[i - 1] == w[j]) {
        t[i] = j + 1;
        j++;
        i++;
      } else if (j > 0) {
        j = t[j];
      } else {
        t[i] = 0;
        i++;
        j = 0;
      }
    }
    return t;
  }

  public boolean kmp(String text, String pattern) {
    int[] arr = computePrefix(pattern.toCharArray());
    int n = text.length(), m = pattern.length();
    int i = 0, j = 0;
    while (i < n) {
      if (text.charAt(i) == pattern.charAt(j)) {
        if (j == m - 1) {
          return true;
        }
        i++;
        j++;
      } else if (j > 0) {
        j = arr[j - 1];
      } else {
        i++;
      }
    }
    return false;
  }

  /**
   * Processes requests for both HTTP
   * <code>GET</code> and
   * <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
      Cookie[] list = request.getCookies();
      Cookie username = null;
      Cookie id = null;
      if (list != null) {
        for (int i = 0; i < list.length; i++) {
          if ("username".equals(list[i].getName())) {
            username = list[i];
          }
          if ("id".equals(list[i].getName())) {
            id = list[i];
          }
        }
      }

      int pagenum = 0;
      int type = 0;
      try {
        pagenum = Integer.parseInt(request.getParameter("pagenumber"));
        type = Integer.parseInt(request.getParameter("type"));
      } catch (Exception e) {
        out.println("KYAKYA");
      }

      int minpost = (pagenum - 1) * 6;
      int maxpost = pagenum * 6;

      String[] query = request.getParameter("q").split(",");

      Class.forName("com.mysql.jdbc.Driver").newInstance();
      String url = "jdbc:mysql://127.0.0.1:3306/progin_171_13509024?user=progin&password=progin";
      Connection conn = DriverManager.getConnection(url);
      Statement statement = conn.createStatement();
      Statement statement2 = conn.createStatement();
      int number = 0;
      ResultSet result;

      if (type == 1) {
        ResultSet temp = statement2.executeQuery("SELECT COUNT(*) FROM tbl_post");
        if (temp.next()) {
          number = temp.getInt(1);
        }
        result = statement.executeQuery("SELECT * FROM tbl_post");
      } else if (type == 2) {
        ResultSet temp = statement2.executeQuery("SELECT COUNT(*) from `tbl_post`order by like_count DESC");
        if (temp.next()) {
          number = temp.getInt(1);
        }
        result = statement.executeQuery("Select * from `tbl_post`order by like_count DESC");
      } else if (type == 3) {
        ResultSet temp = statement2.executeQuery("SELECT COUNT(*) from `tbl_post`order by comment_count DESC");
        if (temp.next()) {
          number = temp.getInt(1);
        }
        result = statement.executeQuery("Select * from `tbl_post`order by comment_count DESC");
      } else {
        ResultSet temp = statement2.executeQuery("SELECT COUNT(*) `tbl_post`");
        if (temp.next()) {
          number = temp.getInt(1);
        }
        result = statement.executeQuery("Select * from `tbl_post`order by update_time DESC");
      }

      int last = (int) Math.ceil((double) number / (double) 6);

      int next = pagenum + 1;
      int previous = pagenum - 1;

      int count = 0;
      try {
        while (result.next()) {
          for (int x = 0; x < query.length; x++) {
            count++;
            if (kmp(result.getString("title"), query[x])) {
              if (id != null) {
                out.print(getContent(Integer.parseInt(id.getValue()), result.getInt(1)));
              } else {
                out.print(getContent(0, result.getInt(1)));
              }
            }
          }
        }
      } catch (Exception e) {
        out.println("HOHOHOHO" + e);
      }

      if (pagenum == 1 && pagenum == last) {
      } else if (pagenum == 1) {
        out.print("<table>"
                + "<tr>"
                + "<td>"
                + "<input type='button' value='Next' onclick='updateContentList(" + next + ")'>"
                + "</td>"
                + "</tr>"
                + "</table>");
      } else if (pagenum == last) {
        out.print("<table>"
                + "<tr>"
                + "<td>"
                + "<input type='button' value='Previous' onclick='updateContentList(" + previous + ")'>"
                + "</td>"
                + "</tr>"
                + "</table>");
      } else {
        out.print("<table>"
                + "<tr>"
                + "<td>"
                + "<input type='button' value='Previous' onclick='updateContentList(" + previous + ")'>"
                + "</td>"
                + "<td>"
                + "<input type='button' value='Next' onclick='updateContentList(" + next + ")'>"
                + "</td>"
                + "</tr>"
                + "</table>");
      }

    } catch (Exception e) {
      out.println(e);
    } finally {
      out.close();
    }
  }

  // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
  /**
   * Handles the HTTP
   * <code>GET</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    processRequest(request, response);
  }

  /**
   * Handles the HTTP
   * <code>POST</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    processRequest(request, response);
  }

  /**
   * Returns a short description of the servlet.
   *
   * @return a String containing servlet description
   */
  @Override
  public String getServletInfo() {
    return "Short description";
  }// </editor-fold>
}
